package cn.lls.service.impl;

import cn.lls.base.common.LlsEnum;
import cn.lls.base.exception.LlsException;
import cn.lls.base.result.ResultCode;
import cn.lls.base.util.EmailUtil;
import cn.lls.base.util.MD5Util;
import cn.lls.dao.CompanyAllInfoDao;
import cn.lls.entity.common.RegionDictEntity;
import cn.lls.entity.company.CompanyAccountEntity;
import cn.lls.entity.company.CompanyBaseEntity;
import cn.lls.entity.company.CompanyHeadEntity;
import cn.lls.req.company.AuditCompanyReq;
import cn.lls.req.company.CompanyReq;
import cn.lls.req.company.ConditionSearchCompanyReq;
import cn.lls.service.*;
import cn.lls.tps.EmailTPS;
import cn.lls.vo.company.CompanyAllInfo;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @ClassName CompanyAllInfoServiceImpl
 * @Author 划水艺术家
 * @Date 2022/11/16 14:25
 * @Version 1.0
 **/
@Service
@Slf4j
public class CompanyAllInfoServiceImpl extends ServiceImpl<CompanyAllInfoDao, CompanyReq> implements ICompanyAllInfoService {

    @Autowired
    private ICompanyBaseService companyBaseService;

    @Autowired
    private ICompanyHeadService companyHeadService;

    @Autowired
    private IRegionDictService regionDictService;

    @Autowired
    private EmailTPS emailTPS;

    @Autowired
    private ICompanyAccountService companyAccountService;

    /*
    公司信息注册，即将信息插入两个表
    */
    @Override
    public void companyEnroll(CompanyReq companyReq) {
        verifyRegionCode(companyReq.getProvinceId(), companyReq.getCityId(), companyReq.getDistrictId());
        CompanyBaseEntity companyBaseEntity = new CompanyBaseEntity();
        BeanUtils.copyProperties(companyReq, companyBaseEntity);
        companyBaseEntity.setIsDeleted(0);
        companyBaseService.save(companyBaseEntity);
        CompanyHeadEntity companyHeadEntity = new CompanyHeadEntity();
        BeanUtils.copyProperties(companyReq, companyHeadEntity);
        companyHeadEntity.setIsDeleted(0);
        companyHeadEntity.setCompanyId(companyBaseEntity.getCompanyId());
        companyHeadService.save(companyHeadEntity);
    }


    @Override
    public void companyUpdate(CompanyReq companyReq) {
        verifyRegionCode(companyReq.getProvinceId(), companyReq.getCityId(), companyReq.getDistrictId());
        CompanyBaseEntity companyBaseEntity = new CompanyBaseEntity();
        BeanUtils.copyProperties(companyReq, companyBaseEntity);
        companyBaseEntity.setIsDeleted(0);
        companyBaseService.updateById(companyBaseEntity);
        CompanyHeadEntity companyHeadEntity = new CompanyHeadEntity();
        BeanUtils.copyProperties(companyReq, companyHeadEntity);
        companyHeadEntity.setIsDeleted(0);
        companyHeadEntity.setCompanyId(companyBaseEntity.getCompanyId());
        LambdaUpdateWrapper<CompanyHeadEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(CompanyHeadEntity::getCompanyId, companyReq.getCompanyId());
        companyHeadService.update(companyHeadEntity, updateWrapper);
    }


    /*
        验证 regionId 的合法性
     */
    private void verifyRegionCode(Integer provinceId, Integer cityId, Integer districtId) throws LlsException{
        try {
            RegionDictEntity district = regionDictService.getById(districtId);
            if (district == null) {
                throw new LlsException(ResultCode.PARAM_ERROR, "区县Id数据异常");
            }
            RegionDictEntity city = regionDictService.getById(cityId);
            if (city == null || !city.getRegionCode().equals(district.getParentCode())){
                throw new LlsException(ResultCode.PARAM_ERROR, "市Id数据异常");
            }
            RegionDictEntity province = regionDictService.getById(provinceId);
            if (province == null || !province.getRegionCode().equals(city.getParentCode())
                    || !province.getParentCode().equals("100000")) {
                throw new LlsException(ResultCode.PARAM_ERROR, "省Id数据异常");
            }
        } catch (Exception e){
            throw new LlsException(ResultCode.PARAM_ERROR, e.getMessage());
        }
    }

    /*
   超级管理员分页条件查询公司
    */
    @Override
    public IPage<CompanyAllInfo> getCompanyInfoByPageAndCondition(ConditionSearchCompanyReq conditionSearchCompanyReq){
        IPage<CompanyAllInfo> page = new Page<>(conditionSearchCompanyReq.getCurrentPage(), conditionSearchCompanyReq.getPageSize());
        return this.baseMapper.getCompanyInfoByPageAndCondition(page, conditionSearchCompanyReq);
    }


    /*
       根据超管行为，做出决策。包括生成账号、密码，发送邮箱
    */
    @Override
    public void executeByBehavior(AuditCompanyReq auditCompanyReq, CompanyBaseEntity companyBase){
        try {
            if (Objects.equals(auditCompanyReq.getBehavior(), LlsEnum.LlsAuditCompanyBehavior.AGREE.getBehavior())){
                // 审核通过
                // 直接分配邮箱为登录账号
                String account = companyBase.getContactEmail();
                // 随机生成 16 位密码
                String loginPassword = EmailUtil.creatCode(16);
                // 数据库保存
                CompanyAccountEntity companyAccountEntity = new CompanyAccountEntity();
                companyAccountEntity.setCompanyId(companyBase.getCompanyId());
                companyAccountEntity.setAccount(account);
                companyAccountEntity.setLoginPassword(MD5Util.MD5Encode(loginPassword));
                companyAccountService.save(companyAccountEntity);
                emailTPS.sendAgreeMessage(companyBase.getCompanyName(), account, loginPassword, companyBase.getContactEmail());
            } else if (Objects.equals(auditCompanyReq.getBehavior(), LlsEnum.LlsAuditCompanyBehavior.REFUSE.getBehavior())){
                // 审核未通过
                emailTPS.sendRefuseMessage(companyBase.getCompanyName(), auditCompanyReq.getMessage(), companyBase.getContactEmail());
            } else if (Objects.equals(auditCompanyReq.getBehavior(), LlsEnum.LlsAuditCompanyBehavior.BANNED.getBehavior())){
                // 封禁公司
                emailTPS.sendBannedMessage(companyBase.getCompanyName(), auditCompanyReq.getMessage(), companyBase.getContactEmail());
            } else {
                // 解封公司
                emailTPS.sendUnblockMessage(companyBase.getCompanyName(), companyBase.getContactEmail());
            }
        } catch (Exception e){
            throw new LlsException(ResultCode.EMAIL_SEND_FAIL);
        }

    }

    /*
    根据公司当前状态判断行为是否合理
    */
    public Boolean verifyBehavior(Integer behavior, Integer companyStatus){
        if (Objects.equals(companyStatus, LlsEnum.LlsCompanyStatus.UNDER_REVIEW.getStatus())
                || Objects.equals(companyStatus, LlsEnum.LlsCompanyStatus.REFUSE.getStatus())){
            // 公司正在等待审核 || 公司未通过审核
            return Objects.equals(behavior, LlsEnum.LlsAuditCompanyBehavior.REFUSE.getBehavior())
                    || Objects.equals(behavior, LlsEnum.LlsAuditCompanyBehavior.AGREE.getBehavior());
        }
        if (Objects.equals(companyStatus, LlsEnum.LlsCompanyStatus.ACTIVE.getStatus())){
            // 公司活动中
            // 只能对其进行 封禁处理
            return Objects.equals(behavior, LlsEnum.LlsAuditCompanyBehavior.BANNED.getBehavior());
        }
        else {
            // 公司封禁
            // 只能对其进行 解封处理
            return Objects.equals(behavior, LlsEnum.LlsAuditCompanyBehavior.UNBLOCK.getBehavior());
        }
    }

    @Override
    public CompanyAllInfo getCompanyById(Long companyId) {
        return this.baseMapper.getCompanyById(companyId);
    }
}
